#include "work_que.h"

//test:
int test()
{
    printf("que test:\n");
    taskQue_t que;
    que_init(&que,9);
    ptaskNode_t tmp;
    printf("enque:\n");
    for(int i = 0;i<10;++i)
    {
        tmp = (ptaskNode_t)calloc(sizeof(taskNode_t),1);
        tmp->fd = i;
        que_set(&que,tmp);
    }
    printf("deque:\n");
    for(int i = 0;i<10;++i)
    {
        if(-1== que_get(&que,&tmp))
        {  
            printf("error in que get\n");
            return 0;
        }
        printf("%d\n",tmp->fd);
        free(tmp);
    }
    return 0;
}

int que_init(ptaskQue_t pque,int capacity)
{
    pque->queCapacity = capacity;
    pque->queHead = NULL;
    pque->queTail = NULL;
    pque->queSize = 0;
    pthread_mutex_init(&pque->queMutex,NULL);
    return 0;
}

int que_set(ptaskQue_t pque,ptaskNode_t pnewNode)
{
    if(pque->queSize == pque->queCapacity)//判满
    {
        fprintf(stderr,"que_set error:task que is full!\n");
        return -1;
    }
    if(pque->queHead)//判空 ：非空 直接尾插入队
    {
        pque->queTail->pNext = pnewNode;
        pque->queTail = pnewNode;
        pque->queSize++;
        printf("que_set :enque success! %d/%d \n",pque->queSize,pque->queCapacity);
    }
    else//空： 改变头尾指针
    {
        pque->queHead = pnewNode;
        pque->queTail = pnewNode;
        pque->queSize++;
        printf("que_set :enque success! %d/%d \n",pque->queSize,pque->queCapacity);
    }
    return 0;
}

int que_get(ptaskQue_t pque,ptaskNode_t *pnode)
{
    if(!pque->queHead)//判空
    {
        fprintf(stderr,"que_get error:task que is empty!\n");
        return -1;
    }
    else //队列非空 出队
    {
        *pnode = pque->queHead;
        if(pque->queSize == 1)
        {
            pque->queHead = NULL;
            pque->queTail = NULL;
        }
        else
        {
            pque->queHead = pque->queHead->pNext;
        }
        pque->queSize--;
        printf("que_get :deque success! %d/%d \n",pque->queSize,pque->queCapacity);
    }
    return 0;
}
